package com.sdx.console.ncode.web;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.Collections;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.console.common.entity.BaseProvince;
import com.sdx.console.common.service.BaseDataService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadMessage;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.console.web.dto.DictExcelImportData;
import com.ibeetl.admin.console.web.query.UserQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.annotation.Query;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.ibeetl.admin.core.util.*;
import com.sdx.common.utils.*;
import com.sdx.console.ncode.entity.*;
import com.sdx.console.ncode.service.*;
import com.sdx.console.ncode.web.query.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.ibeetl.admin.core.web.AuthorizedBaesController;


/**
 * N码 接口
 */
@RequestMapping("/ncode/rightncode")
@Controller
public class RightNcodeController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(RightNcodeController.class);
    private static final String MODEL = "/ncode/rightncode";


    @Resource
	private RightNcodeService rightncodeService;

    @Autowired
    private FileService fileService;

    @Resource
    private SQLManager sqlManager;

    @Resource
    private BaseDataService baseDataService;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {
        RightRole role = new RightRole() ;
        CoreUser user = getLoginUser(request);
        role.setRoleType(1);
        role.setTenantId(user.getTenantId());
        List<RightRole> roleList = sqlManager.template(role);
        view.addObject("roleList",roleList);
	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("ncode.rightncode.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request,Integer batchId) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        view.addObject("batchId",batchId);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("ncode.rightncode.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,String nCode) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        RightNcode rightncode = rightncodeService.queryById(nCode);
        view.addObject("rightncode", rightncode);
		setPageParam(view,request);
        try {
			view.addObject("rightncodeJson", JacksonUtils.toJsonString(rightncode,JacksonUtils.DF1));
		} catch (Exception e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("ncode.rightncode.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("ncode.rightncode.query")
    @ResponseBody
    public JsonResult<PageQuery> list(RightNcode condtion,HttpServletRequest request)
    {
        CoreUser user = getLoginUser(request);
        condtion.setTenantId(user.getTenantId());
        PageQuery page = condtion.getPageQuery();
        rightncodeService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,RightNcode rightncode,HttpServletRequest request
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/cover/"+dir+"/";
		String bucketName = "sdxcomm";
		CoreUser user = getLoginUser(request);

    	if (isNew) {
			rightncode.setCreatedBy(user.getId().intValue());
			rightncode.setCreatedName(user.getName());
			rightncode.setCreatedTime(new Date());
			rightncode.setUpdatedBy(user.getId().intValue());
			rightncode.setUpdatedName(user.getName());
			rightncode.setUpdatedTime(new Date());
			rightncodeService.save(rightncode);
		} else {
			rightncode.setUpdatedBy(user.getId().intValue());
			rightncode.setUpdatedName(user.getName());
			rightncode.setUpdatedTime(new Date());
			rightncodeService.updateTemplate(rightncode);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("ncode.rightncode.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)RightNcode rightncode,HttpServletRequest request
		)
    {

        return save(true,rightncode,request
		);
    }

    @PostMapping("/update.json")
    @Function("ncode.rightncode.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  RightNcode rightncode,HttpServletRequest request
		) {
		return save(false,rightncode,request
		);
    }



    @GetMapping("/view.json")
    @Function("ncode.rightncode.query")
    @ResponseBody
    public JsonResult<RightNcode>queryInfo(String nCode) {
        RightNcode rightncode = rightncodeService.queryById( nCode);
        return  JsonResult.success(rightncode);
    }

    @PostMapping("/delete.json")
    @Function("ncode.rightncode.del")
    @ResponseBody
    public JsonResult delete(String ids,HttpServletRequest request) {
        CoreUser user = getLoginUser(request);
        RightNcode rightncode = new RightNcode();
        rightncode.setUpdatedBy(user.getId().intValue());
        rightncode.setUpdatedName(user.getName());
        rightncode.setUpdatedTime(new Date());
		List<String> idList = Utils.strToList(ids,",");
        rightncodeService.batchDelRightNcode(idList,rightncode);
        return JsonResult.success();
    }

    /**
     * 出库
     * @param ids
     * @param request
     * @return
     */
    @PostMapping("/out.json")
    @Function("ncode.rightncode.out")
    @ResponseBody
    public JsonResult out(String ids,HttpServletRequest request,Integer provinceId) {
        CoreUser user = getLoginUser(request);
        RightNcode rightncode = new RightNcode();
        rightncode.setUpdatedBy(user.getId().intValue());
        rightncode.setUpdatedName(user.getName());
        rightncode.setUpdatedTime(new Date());
        List<String> idList = Utils.strToList(ids,",");
        rightncodeService.updateRightNcodeByIds(idList,rightncode,provinceId);
        return JsonResult.success();
    }

    @PostMapping("/allout.json")
    @Function("ncode.rightncode.allout")
    @ResponseBody
    public JsonResult allout(Integer batchId,HttpServletRequest request,Integer provinceId) {
        CoreUser user = getLoginUser(request);
        RightNcode rightncode = new RightNcode();
        rightncode.setUpdatedBy(user.getId().intValue());
        rightncode.setUpdatedName(user.getName());
        rightncode.setUpdatedTime(new Date());
        rightncodeService.updateRightNcodeByBatchId(batchId,rightncode,provinceId);
        return JsonResult.success();
    }

    @PostMapping("/excel/export.json")
    @Function("ncode.rightncode.export")
    @ResponseBody
    public JsonResult<String> export(HttpServletResponse response,RightNcode condtion,String ids) {
        /**
         * 1)需要用你自己编写一个的excel模板
         * 2)通常excel导出需要关联更多数据，因此rightNcodeService.queryByCondition方法经常不符合需求，需要重写一个为模板导出的查询
         * 3)参考ConsoleDictController来实现模板导入导出
         */
        List<String> idList = new ArrayList<>();
        if(StringUtils.isNotBlank(ids)){
            idList = Utils.strToList(ids,",");
        }
        String excelTemplate ="excelTemplates/ncode/ncode.xls";
        PageQuery<RightNcode> page = condtion.getPageQuery();
        //取出全部符合条件的
        page.setPageSize(Integer.MAX_VALUE);
        page.setPageNumber(1);
        page.setTotalRow(Integer.MAX_VALUE);
        //本次导出需要的数据
        Integer batchId = 0;
        List<RightNcode> list =rightncodeService.queryByExoprt(condtion, idList);          //queryByCondition(page).getList();
        for (RightNcode ncode : list) {
            if(batchId==0){
                batchId = ncode.getBatchId();
            }
            if(ncode.getIsActived()!=null&&ncode.getIsActived()==1){
                ncode.set("isActivedStr","已激活");
            }else{
                ncode.set("isActivedStr","未激活");
            }

            if(ncode.getNStatus()!=null&&ncode.getNStatus()==1){
                ncode.set("isStatusStr","出库");
            }else{
                ncode.set("isStatusStr","入库");
            }

            if(ncode.getNType()!=null){
                if(ncode.getNType()==2){
                    ncode.set("nTypeStr","体验卡");
                }else if(ncode.getNType()==4){
                    ncode.set("nTypeStr","会员卡");
                }
            }
        }
        try(InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate)) {
            if(is==null) {
                throw new PlatformException("模板资源不存在："+excelTemplate);
            }
            FileItem item = fileService.createFileTemp("RightNcode_"+batchId+".xls");
            OutputStream os = item.openOutpuStream();
            Context context = new Context();
            context.putVar("list", list);
            JxlsHelper.getInstance().processTemplate(is, os, context);
            os.close();
            //下载参考FileSystemContorller
            return  JsonResult.success(item.getPath());
        } catch (IOException e) {
            throw new PlatformException(e.getMessage());
        }

    }


    @GetMapping("/getProv.json")
    @ResponseBody
    public List<BaseProvince> getProv( HttpServletRequest request) {
        List<BaseProvince> list = baseDataService.getProvinces();
        return list;
    }


    @RequestMapping("/out.do")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/out.html") ;
        view.addObject("provinceList",baseDataService.getProvinces());
        return view;
    }


}
